﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace PrizePicker
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void menuItemGenerate_Click(object sender, EventArgs e)
        {
            if(listViewWinners.Items.Count > 0)
            {
                DialogResult dialogResult = MessageBox.Show("Are you sure? This action will clear Winners list.",
                                                            "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk,
                                                            MessageBoxDefaultButton.Button1);

               if(dialogResult != DialogResult.Yes)
               {
                   return;
               }
            }

            if(numericUpDownEnd.Value < numericUpDownStart.Value)
            {
                MessageBox.Show("End Value must be greater that Start Value.", "Fail", MessageBoxButtons.OK,
                                MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }

            listViewHopefuls.Items.Clear();
            listViewWinners.Items.Clear();

            int start = (int) numericUpDownStart.Value;
            int end = (int) numericUpDownEnd.Value;

            for (int i = start; i <= end; i++)
            {
                listViewHopefuls.Items.Add(new ListViewItem(i.ToString()));
            }

            menuItemDraw.Enabled = true;
        }

        private void menuItemReset_Click(object sender, EventArgs e)
        {
            listViewHopefuls.Items.Clear();
        }

        private void menuItemDraw_Click(object sender, EventArgs e)
        {
            if (listViewHopefuls.Items.Count == 0)
            {
                MessageBox.Show("Everybody has won something go home.", "Alert", MessageBoxButtons.OK,
                                MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }


            Byte[] randomBytes = new byte[4];

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(randomBytes);

            // Convert 4 bytes into a 32-bit integer value.
            int seed = (randomBytes[0] & 0x7f) << 24 |
                        randomBytes[1] << 16 |
                        randomBytes[2] << 8 |
                        randomBytes[3];

            int pick = seed % listViewHopefuls.Items.Count;

            string winner = listViewHopefuls.Items[pick].Text;
            listViewHopefuls.Items.RemoveAt(pick);

            listViewWinners.Items.Add(new ListViewItem(winner));
        }
    }
}